<template>
  <div>
    <!-- 使用Flex布局使搜索框和工具栏在同一行，并设置位置 -->
    <div class="toolbar-container">
      <!-- 搜索框，靠左 -->
      <p class="search-box">
        <vxe-input v-model="filterName" type="search" placeholder="试试全表搜索" clearable @change="searchEvent"></vxe-input>
      </p>

      <!-- 工具栏，靠右 -->
      <vxe-toolbar ref="toolbarRef" print export custom class="toolbar"></vxe-toolbar>
    </div>
    <div style="height: calc(100vh - 170px)">

      <!-- 数据表格展示 -->
      <vxe-table
          ref="tableRef"
          :print-config="{}"
          :export-config="{}"
          :custom-config="{}"
          border
          class="my-table"
          height="100%"
          :column-config="{useKey: true}"
          :row-config="{useKey: true}"
          :data="list">
        <!-- 复选框列 -->
        <vxe-column type="checkbox" width="60"></vxe-column>

        <!-- 序号列 -->
        <vxe-column type="seq" width="80"></vxe-column>
        <!-- 设备名称 -->
        <vxe-column field="orchardName" title="果园名称" type="html" sortable></vxe-column>
        <!-- 设备状态 -->
        <vxe-column field="accountNo" title="拥有者" type="html" sortable></vxe-column>
        <vxe-column field="orchardAddress" title="地理位置" type="html" sortable></vxe-column>
        <vxe-column field="orchardArea" title="果园面积" type="html" sortable></vxe-column>
        <vxe-column field="creationDate" title="创建时间" type="html" sortable></vxe-column>
      </vxe-table>
    </div>

    <!-- 分页组件 -->
    <vxe-pager
        v-model:currentPage="pageVO.currentPage"
        v-model:pageSize="pageVO.pageSize"
        :total="pageVO.total"
        :layouts="['Home', 'PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'End', 'Sizes', 'FullJump', 'Total']"
        @page-change="pageChange">
    </vxe-pager>
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, reactive } from 'vue'
import type { VxeToolbarInstance, VxeTableInstance } from 'vxe-table'
import XEUtils from 'xe-utils'
import request from "@/util/request.ts";

// RowVO 类型定义，添加索引签名
interface RowVO {
  id: number
  equipmentName: string
  equipmentStatus: string
  [key: string]: any // 添加索引签名，允许使用 string 索引
}

// 使用 ref 获取 vxe-table 和 vxe-toolbar 实例
const toolbarRef = ref<VxeToolbarInstance | null>(null)
const tableRef = ref<VxeTableInstance | null>(null)

// 明确声明 searchProps 为 string[] 类型
const searchProps: string[] = ['equipmentName', 'equipmentStatus']

// 定义响应式数据
const filterName = ref('')
const list = ref<RowVO[]>([])

// 初始化表格数据
const AllList: RowVO[] = []

// 分页数据
const pageVO = reactive({
  total: AllList.length, // 总条数
  currentPage: 1,        // 当前页码
  pageSize: 10          // 每页显示的条数
})

// 加载分页数据
const handlePageData = () => {
  const { pageSize, currentPage } = pageVO
  const filteredData = handleSearch() // 获取过滤后的数据
  pageVO.total = filteredData.length // 更新总条数

  // 根据当前页和每页条数切割数据
  list.value = filteredData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
}

// 分页改变时触发
const pageChange = (params: { currentPage: number, pageSize: number }) => {
  const { pageSize, currentPage } = params
  pageVO.currentPage = currentPage
  pageVO.pageSize = pageSize
  handlePageData()
}

// 搜索函数
const handleSearch = () => {
  const filterVal = String(filterName.value).trim().toLowerCase()
  let filteredData = AllList

  if (filterVal) {
    const filterRE = new RegExp(filterVal, 'gi')
    filteredData = AllList.filter(item =>
        searchProps.some(key => String(item[key]).toLowerCase().includes(filterVal))
    )
    filteredData = filteredData.map(row => {
      // 替换匹配的文本
      const item = XEUtils.clone(row)
      searchProps.forEach(key => {
        item[key] = String(item[key]).replace(filterRE, match => `<span class="keyword-highlight">${match}</span>`)
      })
      return item
    })
  }

  return filteredData
}

// 节流函数
const searchEvent = XEUtils.throttle(function () {
  handlePageData() // 搜索时需要重新分页
}, 500, { trailing: true, leading: true })



// 初始化连接 toolbar 和 table
onMounted(async() => {
  await getAllDevicesList()
  handlePageData()
  const $table = tableRef.value
  const $toolbar = toolbarRef.value
  if ($table && $toolbar) {
    $table.connect($toolbar)
  }

})
const getAllDevicesList = async () => {
  await request.get("/api/orchard-msg/all").then(res => {
    if (res.data.code === '200') {
      AllList.push(...res.data.data)
      console.log(res.data)
    }
  })
}
</script>

<style lang="scss" scoped>
/* Flex 布局容器，确保工具栏和搜索框在同一行，搜索框左对齐，工具栏右对齐 */
.toolbar-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-box {
  flex: 1;
}

.toolbar {
  flex-shrink: 0;
}

/* 关键词高亮样式 */
.my-table {
  ::v-deep(.keyword-highlight)  {
    background-color: #FFFF00;
  }
}
</style>
